import { OrderComponent } from './../order/order.component';
import { NavController, NavParams } from 'ionic-angular';
import { BatchInvtService } from './view/batchOperateInvt';
import { ConfirmParams } from './../../component/primeng/confirm/confirm.module';
import { InventoryService } from './../../service/inventory.service';
import { TablePartyMessageHandle } from './../../common/messageHandle/tablePartyMsgHandle';
import { MdDialog, MdSnackBar, MdSnackBarConfig } from "@angular/material";
import { NavigateService } from './../../service/navigate.service';
import { ObjectCopier } from './../../common/objectCopier';
import { FNCManager, InnerMessageType } from './../../common/fncManager';
import { Order, Cart, Table, TableParty } from './../../model/clerkDataContext';
import { MessageHandleManager } from './../../common/messageHandle/msgHandleMg';
import { MessageBoxService, GrowlMessageType, MessageResult } from './../../component/messageBoxService';
import { PreOrderMessageHandle, OrderMessageHandle } from './../../common/messageHandle/orderMsgHandle';
import { TableMessageHandle } from './../../common/messageHandle/tableMsgHandle';
import { TableService } from './../../service/table.service';
import { Component, OnInit, OnDestroy, animate } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { InvtAmountService } from './view/invtAmount';
import { TableOperateService } from './view/tableOperate';
import { TableOrderService } from './view/tableDetailOrder';
import { RemindOrderService } from './view/remindOrder';
import { loadingMask } from './../../component/decorators';
import { CompletePayMessagehandle } from "../../common/messageHandle/completePayMsgHandle";
import { OrderPickUpService } from "../order/view/orderPickUp";
import { StoreService } from "../../service/store.service";

@Component({
    //moduleId: module.id,
    selector: 'div[table-detail]',
    templateUrl: './tableDetail.component.html',
    styleUrls: ['./tableDetail.component.scss']
})
export class TableDetailComponent implements OnDestroy {
    dialogType: any;
    selectAll: any = false;
    isCloseTable: boolean = false;
    isShowOrder: boolean = false;
    isShowSelectPerple: boolean = false;

    subTitle = "";
    isSelectedAllGroup = false;

    showPickUp = false; // 是否显示叫起按钮

    tableInfo: any = {};
    queryParam: TableQueryParmas = {
        tableZoneId: "",
        tableStatus: ""
    };
    tableGroupList: any[] = [];
    get isMerge(): boolean { return this.tableInfo && this.tableInfo.tableParty && this.tableInfo.tableParty.tableGroupId; };
    title: string;
    currentStore = { id: "" };
    loadingTableInfo: boolean = true;
    private sub;
    private tableId: string;
    // private zoneId: string;
    isShowDetail: boolean = false;
    private tableMsgHandle: TableMessageHandle;
    private preOrderMsgHandle: PreOrderMessageHandle;
    private orderMsgHandle: OrderMessageHandle;
    private tablePartyMsgHandle: TablePartyMessageHandle;
    private completePayMsghandle: CompletePayMessagehandle;
    constructor(
        private tableSvr: TableService,
        private invtSvr: InventoryService,
        private router: NavigateService,
        private acRouter: ActivatedRoute,
        private msgSvr: MessageBoxService,
        private dialog: MdDialog,
        private storeSvr: StoreService,
        public snackBar: MdSnackBar,
        public navCtrl: NavController,
        private navParams: NavParams
    ) { }

    ionViewWillEnter() {
        this.router.registGoBack(this.navGoBack.bind(this));
        this.currentStore = this.tableSvr.CurrentStore;
        // this.sub = this.acRouter.params.subscribe(params => {

        this.tableId = this.navParams.get("tableId");
        // this.zoneId = this.navParams.get('zoneId');
        this.getTableInfo(this.tableId);
        /**
         * 台桌消息处理
         */
        this.tableMsgHandle = MessageHandleManager.Current.GetMessageHanle<TableMessageHandle>("TableMessageHandle");
        this.tableMsgHandle.OnMessage = async (table) => {
            console.log("this.tableMsgHandle.OnMessage", table);
            if (this.tableId != table.id) return;
            if (table.status == "" || table.status == "closed") {
                console.log("台桌结算消息");
                let confirmParams: ConfirmParams = {
                    content: "该台桌已经关台"
                }
                let result = await MessageBoxService.Current.Show(this.dialog, confirmParams);
                this.dialog.closeAll();
                this.navCtrl.pop({ animate: false });
            }
            else {
                this.getTableInfo(table.id);
            }
        }

        this.tablePartyMsgHandle = MessageHandleManager.Current.GetMessageHanle<TablePartyMessageHandle>("TablePartyMessageHandle");
        this.tablePartyMsgHandle.OnMessage = (tableParty) => {
            console.log("this.tablePartyMessageHandle", tableParty);
            if (this.tableId != tableParty.tableId) {
                return;
            }
            this.getTableInfo(this.tableId);
        }

        this.preOrderMsgHandle = MessageHandleManager.Current.GetMessageHanle<PreOrderMessageHandle>("PreOrderMessageHandle");
        this.orderMsgHandle = MessageHandleManager.Current.GetMessageHanle<OrderMessageHandle>("OrderMessageHandle");
        this.preOrderMsgHandle.OnMessage = (order) => {
            // 处理来自其他终端的order消息
            console.log("orderMsgHandle.OnMessage ", order);
            if (order.extended.table.id != this.tableId) return;
            if (!this.tableInfo.orderList) {
                this.tableInfo.orderList = [];
            }
            this.handlePreOrderMsg(this.tableId);
        }
        this.orderMsgHandle.OnMessage = (order) => {
            if (order.extended.table.id != this.tableId) return;
            this.handlePreOrderMsg(this.tableId);
        }
        /**
         * 订单结算消息处理
         */
        this.completePayMsghandle = MessageHandleManager.Current.GetMessageHanle<CompletePayMessagehandle>("CompletePayMessagehandle");
        this.completePayMsghandle.OnMessage = async (tableId) => {
            console.log("this.completePayMsghandle", tableId);
            if (this.tableId != (<any>tableId).id) return;
            let confirmParams: ConfirmParams = {
                content: "该台桌已经关台"
            }
            let result = await MessageBoxService.Current.Show(this.dialog, confirmParams);
            this.dialog.closeAll();
            // this.router.navigate(["table", this.zoneId]);
            this.navCtrl.pop({ animate: false });
        }
    }

    /**
     * orderList的ngfor时的trackBy方法
     */
    trackByFn(index, item) {
        return item.id;
    }

    goBack() {
        this.navCtrl.pop({ animate: false });
    }

    navGoBack() {
        let backBtn = document.getElementById("tabledetail-back-btn");
        if (backBtn) {
            this.dialog.closeAll();
            backBtn.click();
        }
    }

    ngOnDestroy() {
        if (this.sub) {
            this.sub.unsubscribe();
        }

        this.preOrderMsgHandle = null;
        this.tableMsgHandle = null;
    }

    /**
     * 处理订单消息
     */
    async handlePreOrderMsg(tableId) {
        let table = await this.tableSvr.GetTableInfo(tableId);
        this.tableInfo.masterOrder = table.masterOrder;
        let pickupList = this.tableInfo.masterOrder.cart.items.filter(item => {
            return item.extended.pickup == "waiting" && (!item.refundQty || item.qty > item.refundQty);
        });
        if (pickupList && pickupList.length) {
            this.showPickUp = true;
        } else {
            this.showPickUp = false;
        }
        if (table && table.orderList) {
            this.tableInfo.orderList = this.tableSvr.mergeOrderList(table.orderList);
            this.tableInfo.orderList.sort((a, b) => {
                return b.createTime - a.createTime;
            });
        }
    }

    /**
     * 处理退菜订单消息
     */
    handlePreOrderRefundMsg(refundOrder: Order) {
        let orderId = refundOrder.refOrderId[0].id;
        if (orderId) {
            let targetOrder = this.tableInfo.orderList.find(ord => { return ord.id == orderId });
            if (targetOrder) {
                targetOrder.amountDue += refundOrder.amountDue;
                if (targetOrder.cart.items && targetOrder.cart.items.length) {
                    for (let item of targetOrder.cart.items) {
                        let itemOrder = refundOrder.cart.items.find(i => { return i.id == item.id });
                        if (itemOrder) {
                            item.refundQty = item.refundQty ? (item.refundQty += (itemOrder.qty * -1)) : (itemOrder.qty * -1);
                        }
                    }
                }
            }
        }
    }

    async onOpenLeft(sidenav) {
        if (!this.subTitle) {
            return;
        }
        if (sidenav._isOpened) {
            sidenav.close();
            return;
        }
        if (this.tableInfo && this.tableInfo.tableParty && this.tableInfo.tableParty.tableGroupId) {
            this.tableGroupList = [];
            sidenav.open();
            let tbs = await this.tableSvr.GetGroupTables(this.tableInfo.tableParty.tableGroupId);
            for (let item of tbs) {
                if (item.id != this.tableId) this.tableGroupList.push(item);
            }
        }
    }
    /**
     * 台桌切换
     * @param table
     * @param sidenav
     */
    onChangeTable(table, sidenav) {
        sidenav.close();
        this.isSelectedAllGroup = false;
        this.tableGroupList.forEach(element => {
            if (element.id == table.id) {
                element.selected = true;
            } else {
                delete element.selected;
            }
        });
        this.getTableInfo(table.id);
        // this.router.navigate(["table/item", table.id, this.zoneId]);
        //TODO
    }

    async onCloseTable(end) {
        let confirmParams: ConfirmParams = {
            content: "是否关闭当前台桌？"
        }
        let msgResult = await MessageBoxService.Current.Show(this.dialog, confirmParams);
        if (msgResult == MessageResult.Ok) {
            this.handleCloseTable();
        }
        end.close();
    }

    @loadingMask()
    async handleCloseTable() {
        try {
            let result = await this.tableSvr.CloseTable(this.tableInfo.id);
            if (this.tableInfo.tableParty && this.tableInfo.tableParty.tableGroupId) {
                await this.handleCancelMergeTable();
            } else {
                FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, result.table);
                this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "关台成功");
                // this.router.navigate(["table", this.zoneId]);
                this.navCtrl.pop({ animate: false });
            }
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "关台失败");
        }
    }

    /**
     * 确定需要并台或转台的台桌，并提交更改
     */
    @loadingMask()
    async onDialogOK(tableList) {
        try {
            let selectedTables = [];
            for (let item of tableList) {
                if (item.selected) selectedTables.push(item);
            }
            if (selectedTables.length > 0) {
                if (this.dialogType == "trans") {
                    let tableTrans = await this.tableSvr.TransferTable(this.tableInfo.id, selectedTables[0]);
                    //发送转台的台桌信息
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, tableTrans.newTable);
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, tableTrans.oldTable);
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.TablePartyMsg, tableTrans.newTableParty);
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.TablePartyMsg, tableTrans.oldTableParty);
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, tableTrans.masterOrder);
                    let transInfo = {
                        transTable: {
                            fromTN: tableTrans.oldTable.name,
                            toTN: tableTrans.newTable.name,
                            tansTableTime: new Date().getTime()
                        },
                        preOrderList: tableTrans.preOrderList
                    }
                    let that = this;
                    this.tablePrintFNCMsg(that, transInfo);
                    this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "转台成功");

                    this.updateTable(tableTrans.newTable, tableTrans.newTableParty, tableTrans.masterOrder, tableTrans.preOrderList);
                }
                else if (this.dialogType == "merge") {
                    let result = await this.tableSvr.MergeTable(this.tableInfo.id, <any>selectedTables);
                    for (let item of result.tableList) {
                        FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, item);
                    }
                    for (let item of result.tablePartyList) {
                        FNCManager.Current.InnerMessageNotify(InnerMessageType.TablePartyMsg, item);
                    }
                    this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "并台成功");

                    //TODO:
                    this.getTableInfo(this.tableId);
                }
            }
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "操作失败");
        }
    }
    /**
     * 转台打印消息
     * @param that 
     * @param msg 
     */
    tablePrintFNCMsg(that, msg) {
        FNCManager.Current.FNC.Notify({ type: "tablePrint", content: msg }).catch(async (error) => {
            let params: ConfirmParams = {
                title: "打印失败",
                content: "是否重新打印台桌" + msg.fromTN + "转到" + msg.toTN + "的转台信息"
            }
            let result = await MessageBoxService.Current.Show(that.dialog, params);
            if (result == MessageResult.Ok) {
                that.tablePrintFNCMsg(that, msg);
            }
        });
    }

    /**
     * 通知POS打印订单
     * @param that 
     * @param r 
     */
    orderPrintFNCMsg(that, r) {
        FNCManager.Current.FNC.Notify({ type: "orderPrint", content: r }).catch(async (error) => {
            let params: ConfirmParams = {
                title: "打印失败",
                content: "是否重新打印台桌" + that.tableInfo.name + "下的订单,订单编号：" + r.id
            }
            let result = await MessageBoxService.Current.Show(that.dialog, params);
            if (result == MessageResult.Ok) {
                that.orderPrintFNCMsg(that, r);
            }
        });
    }

    /**
     * 显示转台列表
     * @param end
     */
    async onShowTransferDialog(end) {
        let all = { id: "", name: "所有" };
        let tableZoneList = await this.tableSvr.GetTableZoneList();
        if (Array.isArray(tableZoneList)) {
            tableZoneList.unshift(all);
        } else {
            tableZoneList = [];
            tableZoneList.unshift(all);
        }
        let tableListAll = await this.getTableList(this.queryParam);
        let tableList = this.filterOutTable(tableListAll);
        this.dialogType = "trans";
        let list = await TableOperateService.Current.open(this.dialog, this.dialogType, tableZoneList, tableList, this.queryParam.tableZoneId, this.tableInfo);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (list) {
            this.onDialogOK(list);
        }
        end.close();
    }

    /**
     * 并台
     */
    async onShowMergeTableDialog(end) {
        this.dialogType = "merge";
        let tableZoneList = await this.tableSvr.GetTableZoneList();
        let all = { id: "", name: "所有" };
        if (Array.isArray(tableZoneList)) {
            tableZoneList.unshift(all);
        } else {
            tableZoneList = [];
            tableZoneList.unshift(all);
        }
        let tableListAll = await this.getTableList(this.queryParam);
        let tableList = this.reloadSelectedTable(tableListAll);
        let list = await TableOperateService.Current.open(this.dialog, this.dialogType, tableZoneList, tableList, this.queryParam.tableZoneId, this.tableInfo);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (list) {
            this.onDialogOK(list);
        }
        end.close();
    }

    /**
     * 取消并台
     */
    async onCancelMergeTable(end) {
        let confirmParams: ConfirmParams = {
            title: "取消合并",
            content: "台桌'" + this.tableInfo.name + "'取消合并后将会独立结算，取消合并"
        }
        let msgResult = await MessageBoxService.Current.Show(this.dialog, confirmParams);
        if (msgResult == MessageResult.Ok) {
            this.handleCancelMergeTable(end);
        }
    }

    @loadingMask()
    async handleCancelMergeTable(end?) {
        try {
            let result = await this.tableSvr.CancelMergeTable(this.tableInfo);
            if (result.table) {
                FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, result.table);
            }
            if (result.tablePartyList && result.tablePartyList.length) {
                for (let i = 0; i < result.tablePartyList.length; i++) {
                    FNCManager.Current.InnerMessageNotify(InnerMessageType.TablePartyMsg, result.tablePartyList[i]);
                }
            }
            this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "取消合并成功！");
            this.getTableInfo(this.tableId);
            if (end) {
                end.close();
            }
            this.closeTableDailog();
            // this.router.navigate(["table", this.zoneId]);
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "取消合并失败");
        }
    }

    /**
     * 返回上一级
     */
    // onBack() {
    //     // this.router.navigate(["table"]);
    //     this.router.goBack();
    // }

    async onOpenTableOrder() {
        let tableInfo = await TableOrderService.Current.open(this.dialog, this.tableInfo, this.totalCartLength, this.totalAmount);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (tableInfo) {
            this.tableInfo = tableInfo;
            let result = await this.tableSvr.updateTableHeadCount(<any>tableInfo);
            if (result) {
                FNCManager.Current.InnerMessageNotify(InnerMessageType.DeskTableMsg, this.tableInfo);
            }
        }
    }

    /**
     * 跳转到订单页面
     */
    onRedirectToOrder() {
        // this.router.navigate(['order', this.tableInfo.id, this.zoneId], {
        //     key: "table/item",
        //     viewStatus: { order: this.tableInfo.id }
        // });
        this.navCtrl.push(OrderComponent, {
            tableId: this.tableInfo.id
        }, { animate: false })
    }

    /*
    * 计算订单的总金额
    */
    get totalAmount() {
        if (this.tableInfo && this.tableInfo.orderList) {
            let r = 0;
            this.tableInfo.orderList.forEach(x => {
                r += x.amountDue;
            });

            return r;
        }
        return 0;
    }
    get totalCartLength(): number {
        if (this.tableInfo && this.tableInfo.orderList) {
            let r = 0;
            this.tableInfo.orderList.forEach(x => {
                r += x.cart.items.length;
            });
            return r;
        }
        else return 0;
    }

    /**
     * 上菜
     * @param orderItem
     * @param cartItem
     */
    async onServed(preOrder: Order, cartItem: Cart) {
        try {
            if (cartItem.extended && cartItem.extended.pickup && cartItem.extended.pickup == 'waiting') {
                this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "等叫状态不能上菜！");
                return;
            }

            if (!cartItem.extended) cartItem.extended = {};
            let dishupCount = 0;
            if (cartItem.extended.dishup) {
                dishupCount = cartItem.extended.dishup.qty;
            }
            let refundQty = cartItem.refundQty ? cartItem.refundQty : 0;
            let unitType = (cartItem.inventory && (<any>cartItem.inventory.unit)) ? (<any>cartItem.inventory.unit).unitType : "";
            let value = await InvtAmountService.Current.open(this.dialog, "serve", "上【" + cartItem.inventoryName + "】", cartItem.qty, dishupCount, refundQty, null, unitType);
            if (!value) return;

            if (value == "cancel") {
                let preOrderCancel = await this.tableSvr.CancelServed(cartItem.inventoryId, preOrder.id);
                delete cartItem.extended.dishup;
                FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, preOrderCancel);
                return;
            }

            let preOrderFbs = await this.tableSvr.Served(cartItem.inventoryId, cartItem.id, preOrder.id, value);

            cartItem.extended.dishup = {
                operateTime: new Date(),
                operator: this.tableSvr.CurrentUser,
                operatorId: this.tableSvr.CurrentUser.id,
                qty: dishupCount + value,
                status: (dishupCount + value) == cartItem.qty ? "all" : "part"
            }
            await this.getTableInfo(this.tableId);
            //通知上菜消息到其他clerk终端
            FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, preOrderFbs);
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "操作失败");
        }
    }

    isServedAll(item: Cart): boolean {
        let refundQty = item.refundQty ? item.refundQty : 0;
        let dishupQty = (item.extended.dishup && item.extended.dishup.qty) ? item.extended.dishup.qty : 0;
        if ((dishupQty >= item.qty - refundQty) && dishupQty > 0 && refundQty < item.qty) {
            return true;
        } else {
            return false;
        }
    }
    isServed(item: Cart): boolean {
        let refundQty = item.refundQty ? item.refundQty : 0;
        let dishupQty = (item.extended.dishup && item.extended.dishup.qty) ? item.extended.dishup.qty : 0;
        if (dishupQty > 0 && item.qty - refundQty > dishupQty) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 退菜
     * @param  {Cart} item 购物车项数据
     * @param  {Order} preOrder 订单信息
     */
    async onRefuntInvt(item: Cart, preOrder: Order) {
        let dishupQty = (item.extended && item.extended.dishup && item.extended.dishup.qty) ? item.extended.dishup.qty : 0
        let refundQty = item.refundQty ? item.refundQty : 0;
        let unitType = (item.inventory && (<any>item.inventory.unit)) ? (<any>item.inventory.unit).unitType : "";
        let preRefundReason = await this.storeSvr.getStoreConfigs("order.retreat.note.presets");
        let refundMsg = await InvtAmountService.Current.open(this.dialog, "refund", "退【" + item.inventoryName + "】", item.qty, dishupQty, refundQty, preRefundReason, unitType);
        if (refundMsg) {
            let value = refundMsg.value;
            let refundReason = refundMsg.refundReason;
            let cartItem = ObjectCopier.Copy<Cart>(item);
            cartItem.refundQty = value;
            try {
                let refundOrder = await this.tableSvr.RefundOrder(cartItem, preOrder, refundReason);
                if (refundOrder && refundOrder.extended) {
                    delete refundOrder.extended.remind;
                }
                item.refundQty = value;
                let that = this;
                this.orderPrintFNCMsg(that, refundOrder)
                FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, refundOrder);
                this.msgSvr.Growl(GrowlMessageType.Success, this.snackBar, "退单成功！");
                this.getTableInfo(this.tableId);
            }
            catch (err) {
                this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "操作失败");
            }
        }
    }

    /**
     * 取消上菜
     * @param orderItem
     * @param cartItem
     */
    async onCancelServed(orderItem: Order, cartItem: Cart) {
        try {
            let preOrder = await this.tableSvr.CancelServed(cartItem.inventoryId, orderItem.id);
            delete (<any>cartItem).isServed;

            FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, preOrder);
        }
        catch (err) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, err ? err : "取消上菜失败");
        }
    }
    /**
     * 获取台桌列表
     * @param queryParams
     */
    private async getTableList(queryParams: TableQueryParmas) {
        let tbs = await this.tableSvr.GetTableList(queryParams);
        let r = [];
        if (Array.isArray(tbs) && tbs.length) {
            let thisId = this.tableInfo.id;
            r = tbs.filter(tb => {
                return tb.id != thisId;
            });
        }
        return r;
    }

    /**
     * 转台过滤掉不能转台的台桌
     * @param  {} tableList
     */
    private filterOutTable(tableList) {
        let result = [];
        result = tableList.filter(table => {
            if (table.tableParty) {
                return table.tableParty.status != 'opening' && table.tableParty.status != 'presettled';
            } else {
                return table.status != 'opening' && table.status != 'cleaning';
            }
        });
        return result;
    }
    private rightOpened = false;
    private closeTableDailog() {
        this.dialogType = false;
        this.rightOpened = false;
    }

    /**
     * 过滤已经并台的台桌
     * @param tableList
     */
    private reloadSelectedTable(tableList: any[]) {
        let result = [];
        result = tableList.filter(tab => {
            if (tab.tableParty) {
                return !tab.tableParty.tableGroupId && tab.tableParty.status != "presettled";
            } else {
                return tab.status != "cleaning"
            }
        });
        return result;
    }

    /**
     * 获取台桌详情
     * @param  {string} tableId
     */
    @loadingMask()
    private async getTableInfo(tableId: string) {
        this.loadingTableInfo = true;
        let table = await this.tableSvr.GetTableInfo(tableId);
        if (!table.status || table.status == "closed") {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "该台桌未开台");
            // this.router.navigate(["table", this.zoneId]);
            this.navCtrl.pop();
            this.loadingTableInfo = false;
            return;
        }
        this.tableInfo = table;
        this.tableInfo.orderList = this.tableSvr.mergeOrderList(this.tableInfo.orderList);
        this.tableInfo.orderList.sort((a, b) => {
            return b.createTime - a.createTime;
        })
        this.tableId = table.id;
        this.queryParam.tableZoneId = this.tableInfo.zone ? this.tableInfo.zone.id : "";
        this.title = this.tableInfo.name;
        if (this.isMerge) {
            this.subTitle = "（已合并）";
        } else {
            this.subTitle = "";
        }
        // 是否显示叫起按钮
        let pickupList = this.tableInfo.masterOrder.cart.items.filter(item => {
            return item.extended.pickup == "waiting" && (!item.refundQty || item.qty > item.refundQty);
        });
        if (pickupList && pickupList.length) {
            this.showPickUp = true;
        } else {
            this.showPickUp = false;
        }
        this.loadingTableInfo = false;
    }
    /**
     * @param  {Table} table
     * @param  {TableParty} tableParty?
     * @param  {Order} masterOrder?
     * @param  {Order[]} preOrderList?
     */
    private updateTable(table: Table, tableParty?: TableParty, masterOrder?: Order, preOrderList?: Order[]) {
        if (tableParty) (<any>table).tableParty = tableParty;
        if (masterOrder) table.masterOrder = masterOrder;
        if (preOrderList) (<any>table).orderList = this.tableSvr.mergeOrderList(preOrderList);
        this.tableSvr.updateInvtInfo(table);
        this.tableInfo = table;
        this.tableId = table.id;
        this.title = this.tableInfo.name;
        if (this.isMerge) {
            this.subTitle = "（已合并）";
        } else {
            this.subTitle = "";
        }
    }

    //打开催菜dialog
    async openRemindDialog(orderItem: Order, isAll?: boolean) {
        let inventories = [];
        if (orderItem && orderItem.cart.items.length) {
            inventories = orderItem.cart.items;
        }
        let remindOrders: any = await RemindOrderService.current.open(this.dialog, inventories);
        this.router.registGoBack(this.navGoBack.bind(this));
        if (remindOrders) {
            try {
                if (isAll) {
                    remindOrders = this.findCartItem(remindOrders, this.tableInfo.orderList);
                }
                for (let rOrder of remindOrders) {
                    delete rOrder.inventory.pic;
                }
                let remindOrder = await this.tableSvr.RemindOrder(this.tableInfo.masterOrder.id, remindOrders);
                //发送催菜消息到pos
                let that = this;
                this.orderPrintFNCMsg(that, remindOrder);
                //提示成功消息
                this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "催菜成功");
            } catch (err) {
                //提示错误消息
                this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "催菜失败");
            }

        }
    }

    /**
     * 查找preOrder中的购物车项
     * @param cartItems 
     * @param preOrderList 
     */
    findCartItem(cartItems: Cart[], preOrderList: Order[] = []): Cart[] {
        let preOrders = preOrderList.filter((order) => {
            return order.orderType != "pre-order-refund";
        });
        let items: Cart[] = [];
        if (preOrders && preOrders.length) {
            for (let i = 0; i < cartItems.length; i++) {
                for (let preOrder of preOrders) {
                    if (preOrder.cart && preOrder.cart.items && preOrder.cart.items.length) {
                        let target = preOrder.cart.items.find((item) => {
                            return item.id == cartItems[i].id;
                        });
                        if (target) {
                            items.push(target);
                        }
                    }
                }
            }
        }
        return items;
    }

    async TransTableMessage(args) {
        let result = await this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "该台桌已经转台");
        this.getTableInfo(args.newTable.id);
    }

    async MergeTableMessage(args) {

    }

    cancelMergeTableMessage(args) {

    }

    picIsCache(invt) {
        let boo = false;
        if ((<any>window).localCache && (<any>window).localCache.isLocalCacheAvailable()) {
            if ((<any>window).localCache.exists("/api/stores/" + this.currentStore.id + "/inventories/" + invt.id + "/pic/bin")) {
                invt.cachePic = "/local-cache/api/stores/" + this.currentStore.id + "/inventories/" + invt.id + "/pic/bin";
                boo = true;
            }
            return boo
        }
        return boo;
    }
    /**
     * 叫起等叫的项
     */
    async pickUp(end) {
        if (end) {
            end.close();
        }
        let list = this.tableInfo.masterOrder.cart.items.filter(item => {
            return item.extended.pickup == "waiting" && (!item.refundQty || item.qty > item.refundQty);
        });
        if (!list || !list.length) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "没有需要叫起的商品！");
            return;
        }
        let result = await OrderPickUpService.current.open(this.dialog, "pickup", list);
        if (result) {
            try {
                let pickupData = await this.tableSvr.pickup(this.tableInfo, result);
                this.getTableInfo(this.tableId);
                FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, pickupData);
                //叫起消息
                FNCManager.Current.FNC.Notify({ type: "orderPrint", content: pickupData });
            } catch (error) {
                this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, error ? error : "叫起失败");
            }

        }
    }

    hideRefundBtn() {
        if (this.currentStore.id == "70746a62b1d043d2b356bd821dca480e") {
            return false;
        } else {
            return true
        }
    }
    /**
     * 是否展示订单详情
     */
    showOrderDetail(isShowDetail, $event) {
        this.isShowDetail = isShowDetail;
    }
    /**
     * 批量上菜
     * @param orderItem 
     */
    async openBacthInvtDialog(orderItem) {
        let inventories = [];
        if (orderItem && orderItem.cart.items.length) {
            inventories = orderItem.cart.items.filter((item) => {
                if (item.qty == item.refundQty) {
                    return false;
                }
                if (item.extended && item.extended.dishup && item.extended.dishup.qty == item.qty) {
                    return false;
                }
                if (item.extended && item.extended.pickup == 'waiting') {
                    return false;
                }
                return true;
            });
        }
        if (!inventories || !inventories.length) {
            this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "菜品已上齐！");
            return;
        }
        let result: any = await BatchInvtService.current.open(this.dialog, inventories, this.tableInfo.orderList);
        if (result) {
            result.forEach(r => {
                r.operator = this.tableSvr.CurrentUser;
            })
            try {
                let preOrders = await this.tableSvr.batchServed(result);
                if (preOrders && preOrders.length) {
                    this.getTableInfo(this.tableId);
                    this.msgSvr.Growl(GrowlMessageType.Info, this.snackBar, "上菜成功！");
                    for (let preorder of preOrders) {
                        //通知上菜消息到其他clerk终端
                        FNCManager.Current.InnerMessageNotify(InnerMessageType.OrderMsg, preorder);
                    }
                }
            } catch (error) {
                console.log(error);
            }

        }
    }
}

interface TableQueryParmas {
    tableZoneId?: string;
    tableStatus?: string;
}